from datetime import datetime

def add_product(db, user_email, name, description, price, image_folder):
    """添加新商品"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        raise Exception('用户不存在')
    
    # 添加商品
    product_id = db.add_product({
        'name': name,
        'description': description,
        'price': price,
        'image_folder': image_folder,
        'seller_id': user['id'],
        'is_completed': False,
        'buyer_id': -1
    })
    return product_id

def get_products_by_page(db, start, count):
    """获取分页商品列表"""
    products = db.get_all_products()
    for product in products[start:start + count]:
        images = get_product_images(db, product['id'])
        image_urls = []
        for image in images:
            image_urls.append(f"/{image['image_path']}")
        product['images'] = image_urls
    return products[start:start + count]

def search_products(db, keyword):
    """搜索商品"""
    products = db.get_all_products()
    keyword = keyword.lower()
    res_products = []
    for product in products:
        if keyword in product['name'].lower() or \
           keyword in product['description'].lower():
            images = get_product_images(db, product['id'])
            image_urls = []
            for image in images:
                image_urls.append(f"/{image['image_path']}")
            product['images'] = image_urls
            res_products.append(product)
    return res_products

def get_product_details(db, product_id):
    """获取商品详情"""
    product = db.get_product(product_id)
    images = get_product_images(db, product['id'])
    image_urls = []
    for image in images:
        image_urls.append(f"/{image['image_path']}")
    product['images'] = image_urls
    return product

def get_user_products(db, user_email):
    """获取用户发布的商品"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        return []
    
    # 获取用户的商品
    products = db.get_products_by_seller(user['id'])
    for product in products:
        images = get_product_images(db, product['id'])
        image_urls = []
        for image in images:
            image_urls.append(f"/{image['image_path']}")
        product['images'] = image_urls
        
        # 检查卖家查看时间是否早于商品更新时间
        seller_last_view = datetime.strptime(product['seller_last_view_at'], '%Y-%m-%d %H:%M:%S')
        updated_at = datetime.strptime(product['updated_at'], '%Y-%m-%d %H:%M:%S')
        product['has_new_updates'] = seller_last_view < updated_at
    
    return products

def get_user_favorites(db, user_email):
    """获取用户收藏的商品"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        return []
    
    # 获取用户的收藏
    products = db.get_user_favorites(user['id'])
    for product in products:
        images = get_product_images(db, product['id'])
        image_urls = []
        for image in images:
            image_urls.append(f"/{image['image_path']}")
        product['images'] = image_urls
    
        # 为每个商品添加时间检查结果
        # 检查用户查看时间是否晚于商品更新时间
        last_view = datetime.strptime(product['last_view_at'], '%Y-%m-%d %H:%M:%S')
        updated_at = datetime.strptime(product['updated_at'], '%Y-%m-%d %H:%M:%S')
        product['has_new_updates'] = last_view < updated_at
    
    return products

def get_user_transactions(db, user_email):
    """获取用户交易记录"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        return []
    
    # 获取用户作为买家的商品
    buyer_products = db.get_products_by_buyer(user['id'])
    for product in buyer_products:
        images = get_product_images(db, product['id'])
        image_urls = []
        for image in images:
            image_urls.append(f"/{image['image_path']}")
        product['images'] = image_urls
    
    # 获取用户作为卖家的已完成的商品
    seller_products = [p for p in db.get_products_by_seller(user['id']) if p['is_completed']]
    
    # 合并交易记录
    transactions = []
    for product in buyer_products + seller_products:
        transactions.append({
            'product_id': product['id'],
            'product_name': product['name'],
            'price': product['price'],
            'completed_at': product['completed_at'],
            'is_buyer': product['buyer_id'] == user['id'],
            'images': product['images']
        })
    
    return transactions

def get_product_comments(db, product_id):
    """获取商品评论"""
    return db.get_product_comments(product_id)

def add_product_comment(db, product_id, user_email, content, parent_comment_id=-1):
    """添加商品评论"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        raise Exception('用户不存在')
    
    # 添加评论
    comment_id = db.add_comment({
        'product_id': product_id,
        'user_id': user['id'],
        'content': content,
        'parent_comment_id': parent_comment_id
    })
    return comment_id

def delete_product_comment(db, comment_id):
    """删除商品评论"""
    return db.delete_comment(comment_id)

def toggle_product_favorite(db, product_id, user_email):
    """切换商品收藏状态"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        raise Exception('用户不存在')
    
    # 检查是否已收藏
    is_favorite = db.is_favorite(user['id'], product_id)
    
    if is_favorite:
        # 取消收藏
        success = db.remove_favorite(user['id'], product_id)
    else:
        # 添加收藏
        success = db.add_favorite(user['id'], product_id)
    
    return success

def add_product_image(db, product_id, image_path):
    """添加商品图片"""
    image_id = db.add_product_image({
        'product_id': product_id,
        'image_path': image_path
    })
    return image_id

def get_product_images(db, product_id):
    """获取商品的所有图片"""
    return db.get_product_images(product_id)

def delete_product_image(db, image_id):
    """删除单个商品图片"""
    return db.delete_product_image(image_id)

def delete_product_images(db, product_id):
    """删除商品的所有图片"""
    return db.delete_product_images(product_id)

def update_product(db, product_id, name, description, price):
    """更新商品信息"""
    return db.update_product(product_id, {
        'name': name,
        'description': description,
        'price': price
    })

def delete_product(db, product_id):
    """删除商品"""
    # 首先删除商品的所有图片
    delete_product_images(db, product_id)
    
    # 然后删除商品记录
    return db.delete_product(product_id)

def update_product_seller_view_time(db, product_id):
    """更新商品卖家查看时间"""
    return db.update_product_seller_view_time(product_id)

def update_favorite_view_time(db, user_email, product_id):
    """更新用户收藏查看时间"""
    # 首先通过邮箱获取用户ID
    user = db.get_user_by_email(user_email)
    if not user:
        raise Exception('用户不存在')
    
    return db.update_favorite_view_time(user['id'], product_id) 